package com.mlnx.bluwifi.manager;

import com.alibaba.fastjson.JSONObject;
import com.mlnx.bluwifi.manager.datalis.DefaultBpLis;
import com.mlnx.bluwifi.manager.datalis.DefaultSpoLis;
import com.mlnx.bluwifi.manager.datalis.DefaultYouRBpLis;
import com.mlnx.bluwifi.pojo.dto.BluDataInfo;
import com.mlnx.bluwifi.service.WifiBluService;
import com.mlnx.bluwifi.tp.BerrySpoPacket;
import com.mlnx.bluwifi.tp.BlueEcgPacket;
import com.mlnx.bluwifi.tp.Packet;
import com.mlnx.bluwifi.tp.youRbp.YouRBpPacket;
import com.mlnx.bluwifi.tp.zhengkbp.ZhengKBpPacket;
import com.mlnx.bluwifi.utils.SpolanyaUtils;
import com.mlnx.bluwifi.utils.TurnByte;
import com.mlnx.common.utils.MyLog;
import com.mlnx.device.entity.Device;

import java.io.*;
import java.net.URL;
import java.net.URLConnection;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * Created by amanda.shan on 2019/11/18.
 */
public class SpoDataTask implements Runnable {

    static Object syn = new Object();

    MyLog log = MyLog.getLog(getClass());

    private String blueMac;

    private String ip;

    private boolean runFlag;

    private WifiBluService wifiBluService;

    private Map<String, Packet> bluPacketMap = new ConcurrentHashMap<>();


    public SpoDataTask(String blueMac, String ip, WifiBluService wifiBluService) {
        this.blueMac = blueMac;
        this.ip = ip;
        this.wifiBluService = wifiBluService;
    }


    public void start() {
        Thread thread = new Thread(this);
        thread.setName("SpoDataTask:" + blueMac);
        thread.start();

    }

    public void stop() {
        log.info("spo task stop");
        runFlag = false;
    }

    private void decode(String deviceId, byte[] bytes) {
        Packet packet = bluPacketMap.get(deviceId);
        Device device = wifiBluService.getDevice(deviceId);

        if (packet == null) {
            if (device == null) {
                log.error("{} 设备不存在", deviceId);
            } else {
                switch (device.getDeviceTypeId()) {
                    case SPO_DEVICE:
                        bluPacketMap.put(deviceId, new BerrySpoPacket(new DefaultSpoLis(deviceId, wifiBluService)));
                        break;
                    case ZK_BP:
                        bluPacketMap.put(deviceId, new ZhengKBpPacket(new DefaultBpLis(deviceId, wifiBluService)));
                        break;
                    case XIAOLOU_SPO_DEVICE:
                        bluPacketMap.put(deviceId, new BerrySpoPacket(new DefaultSpoLis(deviceId, wifiBluService)));
                        break;
                    case ECG_DEVICE:
                        bluPacketMap.put(deviceId, new BlueEcgPacket());
                        break;
                    case YOUR_BP:
                        bluPacketMap.put(deviceId, new YouRBpPacket(new DefaultYouRBpLis(deviceId, wifiBluService)));
                        break;
                    default:
                        log.error("{} 不支持的设备类型{}", deviceId, device.getDeviceTypeId());

                }
                packet = bluPacketMap.get(deviceId);
            }
        }

        if (packet != null) {

            try {
                switch (device.getDeviceTypeId()) {
                    case SPO_DEVICE:
                        packet.decode(bytes, 10);
                        break;
                    case ZK_BP:
                        packet.decode(bytes, bytes.length);
                        break;
                    case XIAOLOU_SPO_DEVICE:
                        packet.decode(bytes, 10);
                        break;
                    case ECG_DEVICE:
                        packet.decode(bytes,bytes.length);
                        break;
                    case YOUR_BP:
                        packet.decode(bytes,bytes.length);
                        break;
                    default:
                        log.error("{} 不支持的设备类型{}", deviceId, device.getDeviceTypeId());

                }
            } catch (Exception e) {
                log.error(e, "{} 数据包解析出错", device.getDeviceTypeId().getMessage());
            }
        }

    }


    @Override
    public void run() {
        int total=0;
        Long startTime =System.currentTimeMillis();
        runFlag = true;
        while (runFlag) {

            InputStream in = null;
            try {

                log.debug("ap mac:{} 重新开始接收蓝牙数据", blueMac);

                URL url = new URL(SpolanyaUtils.getReceiveDeviceInfo(blueMac, ip));
                URLConnection connection = url.openConnection();
                connection.setReadTimeout(5000);
                in = connection.getInputStream();  //带资源的try-catch语句。自动关闭
                InputStream buffer = new BufferedInputStream(in);

                //将InputStream串链到一个Reader
                Reader reader = new InputStreamReader(buffer);
                BufferedReader bufferedReader = new BufferedReader(reader);
                String str = "";

                while (runFlag) {
                    str = bufferedReader.readLine();
                    if (!((":keep-alive").equals(str) || str.length() == 0)) {
                        String spoValue = str.substring(5);
                        BluDataInfo bluDataInfo = JSONObject.parseObject(spoValue, BluDataInfo.class);
                        total =total+ TurnByte.hexToByteArray(bluDataInfo.getValue()).length;
                        if(startTime+10000<System.currentTimeMillis()){
                            log.info("每10秒共收到"+total);
                            total=0;
                            startTime=System.currentTimeMillis();
                        }
                        decode(bluDataInfo.getId(), TurnByte.hexToByteArray(bluDataInfo.getValue()));
                    }
                }

                log.info("ap mac:{} 接收蓝牙数据线程运行结束", blueMac);

            } catch (Exception e) {
                if (!("Connection timed out: connect".equals(e.getMessage()) || "Read timed out".equals(e.getMessage()))) {
                    log.error(e,"接收蓝牙数据错误 mac:{"+blueMac+"}");
                }

            } finally {
                if (in != null) {
                    try {
                        in.close();
                    } catch (IOException e) {
                        log.error(e, "");
                    }
                }
            }

            try {
                Thread.sleep(3000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    public String toString() {
        return "SpoDataTask{" +
                ", blueMac='" + blueMac + '\'' +
                ", ip='" + ip + '\'' +
                '}';
    }
}
